<?php

namespace api\components;

use api\components\behaviors\BaseBehavior;
use api\traits\ControllerTrait;
use Yii;
use yii\filters\Cors;
use yii\web\Response;

class BaseController extends \yii\rest\ActiveController
{
    use ControllerTrait;

    public $modelClass = '';

    // 序列化输出
    public $serializer = [
        'class' => 'yii\rest\Serializer',
        'collectionEnvelope' => 'data',
    ];

    public function behaviors()
    {
        $lang = Yii::$app->request->headers->get('accept-language');
        Yii::$app->language = strtolower(explode(',', $lang)[0] ?? 'zh-cn');

        $behaviors = parent::behaviors();
        $behaviors = array_merge(['cors' => [
            'class' => Cors::className(),
        ]], $behaviors);
        if (Yii::$app->getRequest()->getMethod() !== 'OPTIONS') {
            // 从 query string token 中验证。看以后设计如果仅此一种，直接放在这里即可。
            // $behaviors['authenticator'] = [
            //     'class' => ApiQueryParamAuth::className(),
            //     'tokenParam' => 'token',
            // ];
            $this->attachBehavior('checkAuth', new BaseBehavior());
        }
        Yii::$app->response->format = Response::FORMAT_JSON;

        return $behaviors;
    }

    public function beforeAction($action)
    {
        return true;
        if (!parent::beforeAction($action)) {
            return false;
        }
        if (Yii::$app->getRequest()->getMethod() !== 'OPTIONS') {
            // BaseBehavior.php
//            @todo srq
//            return true;
            return $this->check();
        }

        return true;
    }

    public function beforeSend($event)
    {
        $response = $event->sender;
        $data = [
            'code' => 200,
            'success' => intval($response->isSuccessful),
            'response' => $response->data ?? ['data' => true],
            'errors' => [],
        ];
        if ($response->data !== null) {
            if (!$response->isSuccessful) {
                $data['errors'] = ['msg' => $response->data['message']];
                $data['code'] = $response->data['status'] ?? 0;
            }
        }
        $response->statusCode = 200;
        $response->data = $data;
    }

    public function init()
    {
        parent::init();
        //绑定beforeSend事件，更改数据输出格式
        Yii::$app->getResponse()->on(Response::EVENT_BEFORE_SEND, [$this, 'beforeSend']);
    }
}
